<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生信息管理系统 - 管理界面</title>
    <link rel="icon" href="<c:url value="/favicon.ico"/>" type="image/x-icon"/>
    <link rel="stylesheet" href="<c:url value="/static/css/layui.css"/>">
    <script src="<c:url value="/static/layui.js"/>"></script>
</head>

<c:if test="${empty sessionScope.login}" var="needLogin">
    <body>
    <script>
        layui.use('layer', function () {
            layer.msg("未登录管理员账户，正在跳转至登录页面...");
            setTimeout(function () {
                location.href = "<c:url value="/login.jsp"/>";
            }, 1000);
        });
    </script>
    </body>
</c:if>

<c:if test="${not pageScope.needLogin}">
    <body style="padding: 15px 0; background-color: #f2f2f2">
    <!-- 页面内容 -->
    <div class="layui-col-md8 layui-col-md-offset2">
        <div class="layui-card">
            <div class="layui-card-header" style="height: 72px">
                <h1 style="line-height: 72px; height: 72px; text-align: center">学生信息管理</h1>
            </div>
            <div class="layui-card-body">
                <p style="text-align: right">
                    <a id="register" href="javascript:void(0);">管理员注册</a>
                    <a id="logout" href="javascript:void(0);">重新登陆</a>
                </p>

                <!-- 待渲染的 LayUI 表格 -->
                <table id="students" lay-filter="students"></table>
            </div>
        </div>
    </div>

    <!-- 表格全局工具栏模板 -->
    <script type="text/html" id="table-toolbar">
        <div class="layui-input-inline" style="padding-right: 10px">
            <input type="text" id="contains" name="contains" lay-verify="required" placeholder="请输入关键词"
                   autocomplete="off"
                   class="layui-input" style="margin-bottom: 2px; font-size: 12px; line-height: 32px; height: 32px">
        </div>
        <div class="layui-btn-container" style="display: inline-block">
            <button class="layui-btn layui-btn-sm" lay-event="query">查询学生</button>
            <button class="layui-btn layui-btn-sm" lay-event="add">录入信息</button>
            <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="delete">批量删除</button>
        </div>
    </script>

    <!-- 表格行工具栏模板 -->
    <script type="text/html" id="row-toolbar">
        <a class="layui-btn layui-btn-xs" lay-event="modify">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
    </script>

    <!-- 模态框模板 -->
    <script type="text/html" id="modal">
        <form id="modal-form" class="layui-form" action="" lay-filter="modal-form">
            <div class="layui-form-item">
                <label class="layui-form-label">卡号</label>
                <div class="layui-input-block">
                    <input type="text" id="modal-card" name="card" lay-verify="required|card" placeholder="请输入卡号"
                           autocomplete="false" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" id="modal-name" name="name" lay-verify="required|name" placeholder="请输入姓名"
                           autocomplete="false" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <input type="radio" id="modal-male" name="gender" value="false" title="男" checked>
                    <input type="radio" id="modal-female" name="gender" value="true" title="女">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">生日</label>
                <div class="layui-input-block">
                    <input type="text" id="modal-birth" name="birth" lay-verify="birth" placeholder="请输入日期"
                           autocomplete="false" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="email" id="modal-email" name="email" lay-verify="email" placeholder="请输入邮箱"
                           autocomplete="false" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <input type="text" id="modal-remark" name="remark" placeholder="请输入备注" autocomplete="false"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-item layui-layer-btn-c">
                <button lay-submit id="modal-yes" lay-filter="modal-yes" class="layui-btn">确定</button>
            </div>
        </form>
    </script>

    <!-- 页面逻辑 -->
    <script>
        // 引入 LayUI
        layui.use(['table', 'form', 'laydate', 'layer', 'jquery'], function () {
            var $ = layui.jquery;
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var table = layui.table;

            // 渲染表格
            var students = table.render({
                elem: '#students',
                url: '<c:url value="/api/student/list"/>',
                method: 'get',
                page: true,
                limits: [5, 10, 20, 30, 50],
                toolbar: '#table-toolbar',
                defaultToolbar: [],
                cols: [[
                    {type: 'checkbox'},
                    {field: 'card', title: '卡号', width: 100, align: 'left', sort: true},
                    {field: 'name', title: '姓名', width: 80, align: 'center'},
                    {
                        field: 'gender', title: '性别', width: 60, align: 'center',
                        templet: function (d) {
                            return d.gender ? "女" : "男";
                        }
                    },
                    {field: 'birth', title: '生日', width: 120, align: 'left', sort: true},
                    {field: 'email', title: '邮件', width: 150, align: 'left'},
                    {field: 'remark', title: '备注', width: 200, align: 'left'},
                    {toolbar: '#row-toolbar', width: 150, align: 'center', fixed: 'right'}
                ]],
            });

            // 管理员注册
            $("#register").click(function () {
                layer.msg("正在跳转至注册页面...");
                setTimeout(function () {
                    location.href = "<c:url value="/register.jsp"/>";
                }, 1000);
            });

            // 登出系统
            $("#logout").click(function () {
                $.ajax({
                    url: "<c:url value="/api/admin/logout"/>",
                    type: 'post',
                    dataType: 'json',
                    success: function (result) {
                        if (result && result.code === 0) {
                            layer.msg("登出成功，正在跳转至登录页面...");
                        } else {
                            layer.msg("登出失败" + (result && result.msg ? ": " + result.msg : "") + "！");
                        }
                        setTimeout(function () {
                            location.href = "<c:url value="/login.jsp"/>";
                        }, 1000);
                    }
                });
            });

            // 注册表单验证方法
            form.verify({
                card: function (value) {
                    if (!/^\d{1,24}$/.test(value)) {
                        return "卡号必须为 1-24 位数字";
                    }
                },
                name: function (value) {
                    if (!/^\p{Alpha}{1,8}$/u.test(value)) {
                        return "姓名必须为 1-8 个位字符";
                    }
                },
                birth: function (value) {
                    if (value && !/^\d{4}-\d{1,2}-\d{1,2}$/.test(value)) {
                        return "生日格式不正确";
                    }
                },
                email: function (value) {
                    if (value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i.test(value)) {
                        return "邮箱格式不正确";
                    }
                }
            });

            // 表格全局工具栏事件
            table.on('toolbar(students)', function (tab) {
                var event = tab.event;
                var checkStatus = table.checkStatus(tab.config.id);

                if (event === 'query') {
                    // 查询学生
                    students.reload({
                        where: {contains: $("#contains").val().trim()},
                        page: {curr: 1}
                    });
                } else if (event === 'add') {
                    // 录入信息
                    layer.open({
                        formType: 1,
                        title: '录入信息',
                        content: $("#modal").text(),
                        area: ['500px', '460px'],
                        btn: false,
                        success: function (_, index) {
                            form.render();
                            laydate.render({elem: '#modal-birth'});
                            form.on('submit(modal-yes)', function () {
                                $.ajax({
                                    url: "<c:url value="/api/student/add"/>",
                                    type: 'post',
                                    data: form.val('modal-form'),
                                    dataType: 'json',
                                    success: function (result) {
                                        if (result && result.code === 0) {
                                            layer.msg("成功添加学生信息！");
                                            students.reload({
                                                where: {contains: ''},
                                                page: {curr: 1}
                                            });
                                        } else {
                                            layer.msg("学生信息添加失败" + (result && result.msg ? ": " + result.msg : "") + "！");
                                        }
                                    }
                                });
                                layer.close(index);
                                return false;
                            });
                        }
                    });
                } else if (event === 'delete') {
                    // 批量删除
                    var ids = checkStatus.data.map(function (each) {
                        return each.id;
                    });
                    if (ids.length === 0) {
                        layer.msg("请选中学生信息再删除！");
                    } else {
                        layer.confirm("是否删除选中的学生信息？", function (index) {
                            $.ajax({
                                url: "<c:url value="/api/student/remove"/>",
                                type: 'post',
                                data: {id: String(ids)},
                                dataType: 'json',
                                success: function (result) {
                                    if (result && result.code === 0) {
                                        layer.msg("选中的学生信息已全部删除！");
                                        students.reload({
                                            where: {contains: ''},
                                            page: {curr: 1}
                                        });
                                    } else {
                                        layer.msg("学生信息删除失败" + (result && result.msg ? ": " + result.msg : "") + "！");
                                    }
                                }
                            });
                            layer.close(index);
                        });
                    }
                }
            });

            // 表格行工具栏事件
            table.on('tool(students)', function (current) {
                var event = current.event;
                var row = current.data;

                if (event === 'modify') {
                    // 修改学生信息
                    layer.open({
                        formType: 1,
                        title: '修改学生信息',
                        content: $("#modal").text(),
                        area: ['500px', '460px'],
                        btn: false,
                        success: function (_, index) {
                            form.render();
                            laydate.render({elem: '#modal-birth'});

                            form.val('modal-form', Object.assign(Object.assign({}, row), {gender: String(row.gender)}));
                            form.render('radio');

                            form.on('submit(modal-yes)', function () {
                                var formData = form.val('modal-form');
                                formData.id = row.id;
                                $.ajax({
                                    url: "<c:url value="/api/student/modify"/>",
                                    type: 'post',
                                    data: formData,
                                    dataType: 'json',
                                    success: function (result) {
                                        if (result && result.code === 0) {
                                            layer.msg("成功修改学生信息！");
                                            current.update(formData);
                                        } else {
                                            layer.msg("学生信息修改失败" + (result && result.msg ? ": " + result.msg : "") + "！");
                                        }
                                    }
                                });
                                layer.close(index);
                                return false;
                            });
                        }
                    });
                } else if (event === 'delete') {
                    layer.confirm("是否删除学生信息？", function (index) {
                        $.ajax({
                            url: "<c:url value="/api/student/remove"/>",
                            type: 'post',
                            data: {id: row.id},
                            dataType: 'json',
                            success: function (result) {
                                if (result && result.code === 0) {
                                    layer.msg("学生信息已删除！");
                                    current.del();
                                } else {
                                    layer.msg("学生信息删除失败" + (result && result.msg ? ": " + result.msg : "") + "！");
                                }
                            }
                        });
                        layer.close(index);
                    });
                }
            });
        });
    </script>
    </body>
</c:if>
</html>
